﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Delta.Engine
{
    public class ContentWrapperLine : IComparable
    {
        public string ContentLine { get; set; }
        public int HashCode { get; set; }

        public ContentWrapperLine(string line)
        {
            ContentLine = line.Replace("\t", new String(' ', 5));
            HashCode = line.GetHashCode();
        }

        public int CompareTo(object obj)
        {
            return HashCode.CompareTo(((ContentWrapperLine)obj).HashCode);
        }
    }

    public class ContentWrapper : IContentMap
    {
        public ContentWrapper(Stream stream)
        {
            ContentStream = stream;
        }

        private Stream _contentStream;

        private List<ContentWrapperLine> _contentLines;

        public Stream ContentStream {
            get
            {
                return _contentStream;
            }
            set
            {
                _contentStream = value;

                _contentLines = new List<ContentWrapperLine>();

                using (StreamReader streamReader = new StreamReader(_contentStream))
                {
                    //_contentStream.Seek(0, SeekOrigin.Begin);

                    //TODO: may need to check max length
                   _contentLines =
                        (from line in streamReader.Lines()
                        select new ContentWrapperLine(line)).ToList<ContentWrapperLine>();
                }
            }
        }

        public List<ContentWrapperLine> ContentLines
        {
            get
            {
                return _contentLines;
            }
            set
            {
                _contentLines = value;
            }
        }

        public int Count()
        {
            if (_contentLines != null)
            {
                return _contentLines.Count;
            }

            return -1;
        }

        public IComparable GetByIndex(int index)
        {
            if (_contentLines != null)
            {
                if (_contentLines.Count >= index)
                {
                    return _contentLines[index];
                }
            }
            return null;
        }
    }

    public static class StreamReaderSequence
    {
        public static IEnumerable<string> Lines(this StreamReader source)
        {
            String line;

            if (source == null)
                throw new ArgumentNullException("source");
            while ((line = source.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }
}
